var expertId=666;
var questionPay=1;
var show_pay=1;
var pathimg=[];
var datas;
var b=[];
var ihave=0;
var wxNum;
var imgPath="ddd";
var userInfo;
var info="";
var niming=true;
var qiniuUploader = require("../../qiniuUploader.js");
var time=require("../../../utils/util.js");
var uploadimage = function (res) {

  for (var i = 0; i < res.length; i++) {

    qiniuUploader.upload(res[i], (res) => {
      console.log("上传成功")
    },
      (error) => {
        console.log("上传失败")
      },
      {
        uploadURL: 'https://up.qiniup.com',
        region: 'ECN',

        domain: 'www.liuxuanlong.club',
        uptokenURL: 'https://www.liuxuanlong.xyz/fenda/wx/upToken'
      }
    );

  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prompt:"向专家提问",
    disabled:false,
    userImg:"none",
    pathImg:"",
    toast:true,
    fail:"none",
    modal1:true,
    modal2:true,
    modal3:true,
    text:"",
    expert:"",
    name:"",
    info:"",
    goodAt:"",
    headImg:"",
    NoshowQue:'display',
    showQue:'none',
    placeholder:"向专家提问，等他语音回答，回答内容只有你和专家可见；超过48小时未回答，将按支付路径全额退款"
  },

  pay: function () {
    var that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: 'https://www.liuxuanlong.xyz/fenda/wx/falvPay',
            data: {
              code: res.code,
              total_fee: questionPay
            },
            success: function (res) {
              console.log(res.data, '订单号');
              show_pay=1;
              var out_trade_no = res.data.out_trade_no;
              wx.requestPayment(
                {
                  'appid': res.data.appid,
                  'timeStamp': res.data.timeStamp,
                  'nonceStr': res.data.nonceStr,
                  'package': res.data.package,
                  'signType': 'MD5',
                  'paySign': res.data.paySign,
                  'success': function (res) {

                    that.confirm(out_trade_no);
                  },
                  'fail': function (res) {
                    console.log('打印', res);
                  },
                  'complete': function (res) {
                    console.log("666")
                  }
                })
              /*wx.setStorage({
                key: "login_uuId",
                data: res.data
              });*/


              console.log('登录完毕')
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.avatarUrl)
        }
      }
    })
  },
  niming:function(e){
    niming=e.detail.value;
    console.log(niming);
  },
  goto:function(uuid){
   wx.redirectTo({
     url: '../../mine/myquestion/myquestion?uuid=' + uuid,
   })
  },
  modal2:function(){              //问题为空时的提醒
    this.setData(
      {
        modal2:true,
        disabled: false,
        prompt:"向专家提问",
        placeholder:"向专家提问，等他语音回答，回答内容只有你和专家可见；超过48小时未回答，将按支付路径全额退款"
      }
    );
  },
  confirm: function (out_trade_no){                                                       //确认提交
    var that=this;
    var times = time.formatTime(new Date());
    var Time=Date.now();
    if(niming==true)
    niming='true';
    else
    niming='false';
    info=datas.question;
    wx.getStorage({
      key: 'login_uuId',
      success: function(res) {
        wxNum=res.data;
        wx.request({
          url: "https://www.liuxuanlong.xyz/fenda/wx/addQuestion",
          data: {
            wxNumber: wxNum,
            info: info,
            imgPath: pathimg,
            time: times,
            timeNum: Time,
            kind: "",
            isOneMaster: expertId,
            headImg: userInfo.avatarUrl,
            nickName: userInfo.nickName,
            isAnonymous: niming,
            total_fee: questionPay,
            out_trade_no: out_trade_no


          },
          method: 'GET',

          success: function (res) {

            uploadimage(pathimg);
            pathimg = [];
            that.setData(
              {
                modal1: true,
                toast: false,
                or: "提交成功",
                disabled: false,
                text: "",
                userImg: "none",
                placeholder:"向专家提问，等他语音回答，回答内容只有你和专家可见；超过48小时未回答，将按支付路径全额退款"

              }
            );
            that.goto(res.data);
          },
          fail: function () {
            that.setData(
              {
                text: datas.question,
                modal1: true,
                or: "提交失败!请检查网络",
                disabled: true,
                fail: "display",
                placeholder: "向专家提问，等他语音回答，回答内容只有你和专家可见；超过48小时未回答，将按支付路径全额退款"


              }
            );
          },
        })
      },
    })
  
  },
  nowarn:function(){
    this.setData(
      {
        fail:"none",
        disabled:false
      }
    );
  },
  toastHidden:function(){                   //toast 隐藏
    this.setData(
      {
        toast:true,
        //modal3:false
      }
    );
  },
  cancel:function(){                    //取消提交 
    this.setData(
      { 
        text:datas.question,
        modal1:true,
        disabled: false,
        placeholder: "向专家提问，等他语音回答，回答内容只有你和专家可见；超过48小时未回答，将按支付路径全额退款"
      }
    );
  },
  userInfoHandler:function(){
    var that=this;
        wx.getUserInfo({
          success:function(res){
            userInfo=res.userInfo;
            console.log(userInfo);
            ihave=1;
            if (datas.question != "") {
              that.setData(
                {
                 // text: "",
                  //placeholder: " ",
                 
                  //prompt: "",
                  disabled: true,
                 
                }
              );
              if(show_pay==1){
              wx.showToast({
                title: '加载中...',
                icon:'loading',
                duration:500
              })
              that.pay();
              show_pay=0;
              }
            }
            else {
              that.setData(
                {
                  text:"",
                  modal2: false,
                  disabled: true,
                  placeholder: " "
                  //prompt: " "
                }
              );
            }
          },
        })
  },
  send:function(e){                                 //提问按钮 获取数据  选择后续操作
    datas=e.detail.value;
  
  },
  userImg:function(){                             //选择图片
    var that = this;
    var chooseMax = 3 - pathimg.length;
    wx.chooseImage({
      count: chooseMax, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        // success
        pathimg = pathimg.concat(res.tempFilePaths);
        that.showimgs(res.tempFilePaths);
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  previewImg: function (e) {                      //用户预览图片
    
    var index = e.currentTarget.id;
    var prewImg = [];
    prewImg.push(pathimg[index]);
    for (var i = 0; i < pathimg.length; i++) {
      if (i != index)
        prewImg.push(pathimg[i]);
    }
    wx.previewImage({
      current: '',
      urls: prewImg,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  cancelImg: function (e) {                       //用户取消图片

    var index = e.currentTarget.id;
    pathimg.splice(index, 1);
    b.splice(index, 1);
    this.setData(
      {
        usersImg: b,
        /*imgs1: "none",
        imgNum: 0,
        iconX:"none"*/
      }
    );
    if (pathimg.length < 3) {
      this.setData(
        {
          imgSwitch: "display"
        }
      );
    }
   
  },
  showimgs: function (imgs) {                      //用户上传之前预览点击

    if (pathimg.length >= 3)
      this.setData(
        {
          imgSwitch: "none"
        }
      );
    else {
      this.setData(
        {
          imgSwitch: "display"
        }
      );
    }
    var a = { "src": "", "show": "" };


    for (var i = 0; i < imgs.length; i++) {

      a.src = imgs[i];

      a.show = 'display';
      b.push(a);
      a = { "src": "", "show": "" };

    }
    
    this.setData(
      {
        /*usersImg:pathimg[0],
        imgs1:"display",
        imgNum:length,
        iconX:"display"*/
        usersImg: b
      }
    );
  },
  Loadexpert:function(id){
    var that=this;
    wx.request({
      url: "https://www.liuxuanlong.xyz/fenda/wx/findMasterById",
      data:{
        masterId:id
      },
      method:"GET",
      success:function(res){
        console.log('专家信息',res.data)
       
        that.setData(
          {
           name:res.data.name,
           info:res.data.info,
           goodAt:res.data.goodAt,
           headImg:res.data.headImg,
           NoshowQue:'none',
           showQue:'display',
           questionPay:res.data.askMoney*0.01,
           answerNum:res.data.masterAnswerList.length
          }
        );
        
      },
      fail:function(){
        //断网了
      },
    })
  },
  onLoad: function (options) {
    console.log(options);
    wx.setNavigationBarTitle({
      title: options.name,
    })
    expertId=options.id;
    console.log(options.id);
    this.Loadexpert(options.id);
    b = [];
    pathimg = [];
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})